package com.tian.consumer;

import com.alibaba.fastjson.JSON;
import com.tian.entity.SysLog;
import com.tian.mapper.SysLogMapper;
import com.tian.message.SysLogMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author tianwc  公众号：java后端技术全栈、面试专栏
 * @version 1.0.0
 * @date 2023年05月14日 22:22
 * 博客地址：<a href="http://woaijava.cc/">博客地址</a>
 * <p>
 * 日志消费者 落库
 */
@Slf4j
@Component
public class SysLogConsumer {

    @Resource
    private SysLogMapper sysLogMapper;

    @RabbitListener(queues = {"${rabbitmq.sys.log.queue.name}"})
    public void onMessage(String msg) {
        try {
            log.info(msg);
            SysLogMessage sysLogMessage = JSON.parseObject(msg, SysLogMessage.class);
            SysLog sysLog = convert(sysLogMessage);
            sysLogMapper.insert(sysLog);
        } catch (Exception e) {
            log.error("消费者异常：e", e);
        }
    }

    private SysLog convert(SysLogMessage sysLogMessage) {
        SysLog sysLog = new SysLog();
        sysLog.setMethodName(sysLogMessage.getMethodName());
        sysLog.setCreateTime(sysLogMessage.getCreateTime());
        sysLog.setMethodDesc(sysLogMessage.getMethodDesc());
        sysLog.setCostTime(sysLogMessage.getCostTime());
        sysLog.setRequestParam(sysLogMessage.getRequestParam());
        sysLog.setResponseParam(sysLogMessage.getResponseParam());
        sysLog.setIp(sysLogMessage.getIp());
        sysLog.setUrl(sysLogMessage.getUrl());
        return sysLog;
    }
}


